package com.caption.jdk.date;

import java.time.*;
import java.time.format.DateTimeFormatter;

public class TestDate {

    public static void main(String[] args) {
        /**
         * 时间格式化成string
         */
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String str = now.format(formatter);
        System.out.println(str);
        /**
         * string格式化成LocalDateTime
         */
        LocalDateTime dateTime = LocalDateTime.parse("2020-12-03 22:10:30", formatter);
        System.out.println(dateTime);
        /**
         * 时间修改,注意 每次修改时间时对象的本身是不会被修改，只会生成新的对象。
         */
        LocalDateTime updateYear = dateTime.withYear(2019);
        System.out.println(updateYear);
        /**
         * 修改月份
         */
        LocalDateTime updateMonth = dateTime.withMonth(06);
        System.out.println(updateMonth);
        /**
         * 修改天数
         */
        System.out.println(dateTime.withDayOfMonth(27));
        /**
         * 加上指定天数
         */
        System.out.println("两天后=" + now.plusDays(2));
        System.out.println("3个月之后=" + now.plusMonths(3));
        /**
         * 减去指定天数
         */
        System.out.println("5天前" + now.minusDays(5));
        System.out.println("1年前" + now.minusYears(1));
        /**
         * 日期的比较
         */
        LocalDateTime nowTime = LocalDateTime.now();
        LocalDateTime compareTime = LocalDateTime.of(2020, 1, 3, 12, 30, 50);
        System.out.println(nowTime.isAfter(compareTime));
        System.out.println(nowTime.isBefore(compareTime));
        System.out.println(nowTime.isEqual(compareTime));
        /**
         * 计算两个时间差
         */
        LocalTime time = LocalTime.now();
        LocalTime cTime = LocalTime.of(20, 20, 30);
        Duration duration = Duration.between(cTime, time);
        System.out.println("两个时间相差小时=" + duration.toHours());
        System.out.println("两个时间相差分钟=" + duration.toMinutes());
        System.out.println("两个时间相差秒=" + duration.toMillis());
        /**
         * 计算两个日期差
         */
        LocalDate nowDate = LocalDate.now();
        LocalDate cNowDate = LocalDate.of(2020, 5, 6);
        Period period = Period.between(nowDate, cNowDate);
        System.out.println("两个日期相差天数="+period.getDays());
        System.out.println("两个日期相差月数="+period.getMonths());
        System.out.println("两个日期相差年份="+period.getYears());


    }
}
